// GpsBindService.java
package com.example.app3_1;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import android.content.pm.PackageManager;
import android.Manifest;

public class GpsBindService extends Service {
    private static final String TAG = "GpsBindService";
    private LocationManager locationManager;
    private GpsCallback callback;

    // 位置监听器
    private LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Log.d(TAG, "位置更新: " + location.getLatitude() + ", " + location.getLongitude());
            if (callback != null) {
                callback.onLocationUpdated(location.getLatitude(), location.getLongitude());
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}

        @Override
        public void onProviderEnabled(String provider) {
            Log.d(TAG, "GPS提供者启用: " + provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.d(TAG, "GPS提供者禁用: " + provider);
        }
    };

    // 回调接口：用于向Activity传递经纬度
    public interface GpsCallback {
        void onLocationUpdated(double latitude, double longitude);
    }

    // Binder内部类：提供Service实例
    public class GpsBinder extends Binder {
        public GpsBindService getService() {
            return GpsBindService.this;
        }
    }

    private final IBinder binder = new GpsBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "Service被绑定");
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "Service创建");
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    }

    // 注册回调（Activity调用）
    public void setCallback(GpsCallback callback) {
        this.callback = callback;
        startLocationListening();
    }

    // 开始GPS监听
    private void startLocationListening() {
        Log.d(TAG, "开始GPS监听");

        // 检查权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "没有位置权限，无法启动GPS监听");
            return;
        }

        try {
            // 注册位置监听
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    1000, // 1秒更新一次
                    1,    // 位置变化1米即更新
                    locationListener);

            // 同时监听网络位置，提高可用性
            locationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER,
                    1000,
                    1,
                    locationListener);

            Log.d(TAG, "GPS监听已启动");
        } catch (SecurityException e) {
            Log.e(TAG, "启动GPS监听失败，权限异常", e);
        } catch (Exception e) {
            Log.e(TAG, "启动GPS监听失败", e);
        }
    }

    // 停止GPS监听
    private void stopLocationListening() {
        Log.d(TAG, "停止GPS监听");
        if (locationManager != null) {
            locationManager.removeUpdates(locationListener);
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "Service解绑");
        stopLocationListening();
        callback = null; // 清除回调，避免内存泄漏
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "Service销毁");
        stopLocationListening();
    }
}